const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()

  return [year, month, day].map(formatNumber).join('.') + ' ' + [hour, minute].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  formatTime: formatTime
}

function PrefixInteger(num, length) {
   return (Array(length).join('0') + num).slice(-length);
}

var CryptoJS = require('aes.js');  //引用AES源码js
var key = CryptoJS.enc.Utf8.parse("1234567812345678");//十六位十六进制数作为秘钥
var iv = CryptoJS.enc.Utf8.parse('1234567812345678');//十六位十六进制数作为秘钥偏移量
//解密方法
function Decrypt(word) {
  var encryptedHexStr = CryptoJS.enc.Hex.parse(word);
  var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  var decrypt = CryptoJS.AES.decrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.ZeroPadding });
  var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
}
//加密方法
function Encrypt(word) {
  var srcs = CryptoJS.enc.Utf8.parse(word);
  var encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.ZeroPadding });
  return encrypted.ciphertext.toString();
}
//加密方法
function EncryptQR(guardCardNo, hour, min, time) {
  var timestamp = Date.parse(new Date()) / 1000;
  var duration = hour * 60 * 60 + min * 60;
  var word = guardCardNo + '' + timestamp + '' + PrefixInteger(duration, 5) + formatNumber(time) + '00000';
  return Encrypt(word);
}

//暴露接口
module.exports.formatNumber = formatNumber;
module.exports.PrefixInteger = PrefixInteger;
module.exports.EncryptQR = EncryptQR;
module.exports.Decrypt = Decrypt;
module.exports.Encrypt = Encrypt;
